package com.hi.hiparty.ui.fragment;

import org.json.JSONObject;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.hi.hiparty.R;
import com.hi.hiparty.entity.UserInfo;
import com.hi.hiparty.entity.param.ParamUtil;
import com.hi.hiparty.ui.session.UserSessionManager;
import com.hi.hiparty.util.ApiHelper;
import com.hi.hiparty.util.Constants;
import com.hi.hiparty.util.HttpUtil;
import com.hi.hiparty.util.ImageUtil;
import com.hi.hiparty.util.LocationUtil;
import com.hi.hiparty.util.PictureHandler;
import com.hi.hiparty.util.Executor;
import com.hi.hiparty.util.StringUtils;
import com.hi.hiparty.util.UpLoaderPicUtil;

public class EditUserFragment extends SherlockFragment implements View.OnClickListener{
	public static final String TAG = EditUserFragment.class.getSimpleName();
	static {
        PictureHandler.getInstance("picHandler").addCommondForCode(
        		PictureHandler.REQUEST_USEREDIT_CROP, new Executor() {
    			public void excute() {
    				  Bundle extras = this.getIntent().getExtras();
    			        if(extras != null ) {
    			        	Bitmap photo = extras.getParcelable("data");
    			        	try {
    			        		photo = ImageUtil.createBitmapBySizelimit(photo,80);
    			        		ImageUtil.saveJPGE_After(photo, Constants.USER_HEAD_PIC);
    			        		ImageView img =(ImageView)this.getActivity().findViewById(R.id.image_user);
    			        		img.setImageBitmap(photo);
    			        		UpLoaderPicUtil.uploadUserAvatar(Constants.USER_HEAD_PIC, getActivity());
    			        	} catch (Exception e) {
    			        		e.printStackTrace();
    			        	}
    			}	
    		}});
	}
	private EditText editTextNick;
	private EditText editTextMood;
	private EditText editTextCareer;
	private EditText editTextInterest;

	private PictureHandler picHandler = PictureHandler.getInstance("picHandler");
	
	public class UpdateUser extends AsyncTask<String, Void, Boolean>{
		protected void onPostExecute(final Boolean success) {
			if(success)
			Toast.makeText(getActivity(), "更新信息成功", Toast.LENGTH_SHORT).show();
			else
				Log.v("updateUserinfo", "更新用户信息异常");
		}
		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			UserInfo user = UserInfo.builder();
			user.setUserid(UserSessionManager.getUserSession(getActivity()).getUserid());
			user.setInterest(editTextInterest.getText().toString());
			user.setNickname(editTextNick.getText().toString());
			user.setMood(editTextMood.getText().toString());
			user.setCareer(editTextCareer.getText().toString());
			user.getPostMethodParams();
			String resultString = HttpUtil.POST(ApiHelper.API_USER_INFO_UPLOAD,user.getPostMethodParams());
			JSONObject json;
			try {
				json = new JSONObject(resultString);
				if (json.getInt("success") == 1) {
					return true;
				}else{
					return false;
				}
			} catch (Exception e) {
				return false;
			}
		}
		
	}
	public class GetUserTask extends AsyncTask<String, Void, Boolean> {
		UserInfo user = UserInfo.builder();
		protected void onPostExecute(final Boolean success) {
			if(!success)
				Toast.makeText(getActivity(), "网络信息不太好...", Toast.LENGTH_SHORT).show();
			else{
				//更新
				if(StringUtils.isNotBlank(user.getCareer())){
					editTextCareer.setText(user.getCareer());
				}
				if(StringUtils.isNotBlank(user.getMood())){
					editTextMood.setText(user.getMood());
				}
				if(StringUtils.isNotBlank(user.getInterest())){
					editTextInterest.setText(user.getInterest());
				}
				if(StringUtils.isNotBlank(user.getNickname())){
					editTextNick.setText(user.getNickname());
				}
				Log.v("updateUserinfo", "获取用户信息完成");
			}
		}
		protected Boolean doInBackground(String... arg0) {
			user.setUserid(UserSessionManager.getUserSession(getActivity()).getUserid());
			String resultString = HttpUtil.GET(ApiHelper.API_USER_INFO_GET+"?"+user.getGetMethodStr());
			JSONObject json;
			try {
				json = new JSONObject(resultString);
				if (json.getInt("success") == 1) {
					ParamUtil.fromJSONO2Object(user, UserInfo.class, json);
					return true;
				}else{
					return false;
				}
			} catch (Exception e) {
				Log.v("getUser", e.toString());
				return false;
			}
		}
		
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		final View view = inflater.inflate(R.layout.edit_userinfo, container, false);
        editTextNick = (EditText)view.findViewById(R.id.editText_nick);
        editTextMood = (EditText)view.findViewById(R.id.editText_mood);
    	editTextCareer = (EditText)view.findViewById(R.id.editText_career);
    	editTextInterest = (EditText)view.findViewById(R.id.editText_interest);

    	((Button)view.findViewById(R.id.btn_edit_user_camera)).setOnClickListener(this);
        ((Button)view.findViewById(R.id.btn_edit_user_album)).setOnClickListener(this);
        ((Button)view.findViewById(R.id.btn_submit_update_user)).setOnClickListener(this);
        ((Button)view.findViewById(R.id.btn_back_home)).setOnClickListener(this);
        ((Button)view.findViewById(R.id.btn_user_location)).setOnClickListener(this);
        ImageView img =(ImageView)view.findViewById(R.id.image_user);
        img.setImageBitmap(ImageUtil.getBitmapForPath(Constants.USER_HEAD_PIC));
        
        new GetUserTask().execute();
		return view;
	}
    
	//必须用Fragment附着的activity 的onactivityResult
    public void onActivityResult(int requestCode, int resultCode, Intent data){
    }
    
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		getSherlockActivity().getSupportActionBar().setTitle(getString(R.string.activity_title_square));
		getSherlockActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSherlockActivity().getSupportActionBar().setHomeButtonEnabled(true);
	}
    
	@Override
	public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			getSherlockActivity().getSupportFragmentManager().popBackStack();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_submit_update_user:
			new UpdateUser().execute();
			break;
		case R.id.btn_edit_user_camera:
			Log.v(TAG, "调用相机");
			//调用
	      	picHandler.startActivityCamera(getSherlockActivity(),PictureHandler.REQUEST_USEREDIT_CAMERA);
			break;
		case R.id.btn_edit_user_album:
			Log.v(TAG, "调用相册");
    		picHandler.startActivityAlbum(getSherlockActivity(),PictureHandler.REQUEST_USEREDIT_ALBUM);
			break;
		case R.id.btn_user_location:
			Log.v(TAG, "个人位置");
			LocationUtil.showUserLocation(getSherlockActivity());
			break;
		case R.id.btn_back_home:
			getSherlockActivity().getSupportFragmentManager().popBackStack();
			break;
		default:
			return;
		}
	}
}
